import requests
import json
import os
import time


def send_chat_message(api_key, query, conversation_id="", user_id="abc-123", files=None):
    """
    发送聊天消息到API端点

    :param api_key: API认证密钥
    :param query: 用户查询内容
    :param conversation_id: 可选，会话ID
    :param user_id: 可选，用户ID
    :param files: 可选，文件列表
    :return: 响应对象
    """
    url = "http://8.136.111.93:8008/v1/chat-messages"
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }

    # 从JSON文件读取数据
    json_file = os.path.join(os.path.dirname(
        __file__), 'fill_in_blank_question.json')
    with open(json_file, 'r', encoding='utf-8') as f:
        question_data = json.load(f)

    payload = {
        "inputs": {
            "courseName": "生物",
        },
        "query": json.dumps(question_data, ensure_ascii=False),
        "response_mode": "blocking",  # 固定为阻塞模式
        "conversation_id": conversation_id,
        "user": user_id,
        "files": files or []
    }

    retry_count = 3  # 重试次数
    timeout = 30     # 超时时间(秒)

    for attempt in range(retry_count):
        try:
            response = requests.post(
                url,
                headers=headers,
                json=payload,
                timeout=timeout
            )
            try:
                print("原始响应内容:", response.text)
                response.raise_for_status()
                return response.json()
            except requests.exceptions.RequestException as e:
                print(f"请求失败: {e}")
                return {"error": str(e)}
            except json.JSONDecodeError as e:
                print(f"JSON解析失败: {e}")
                return {"error": "Invalid JSON response", "raw_response": response.text}
        except requests.exceptions.Timeout:
            print(f"请求超时，正在重试 ({attempt + 1}/{retry_count})")
            if attempt == retry_count - 1:
                return {"error": "请求超时，请稍后再试"}
            time.sleep(5)  # 等待5秒后重试
        except requests.exceptions.RequestException as e:
            print(f"请求失败: {e}")
            return {"error": str(e)}


if __name__ == "__main__":
    api_key = "app-Zi524Vvwmtfn9xKwwtJ9r9ul"
    query = "智能补全"

    print("\nstarttttt")
    response_data = send_chat_message(api_key, query)  # 移除了stream参数

    # 打印并保存响应数据
    print("\n======= 完整数据 =======")
    print(json.dumps(response_data, indent=2, ensure_ascii=False))
    print("=======================")

    # 保存到文件
    output_file = os.path.join(os.path.dirname(__file__), 'response_data.json')
    with open(output_file, 'w', encoding='utf-8') as f:
        json.dump(response_data, f, indent=2, ensure_ascii=False)
    print(f"\n数据已保存到: {output_file}")
